﻿// Copyright (c) 2009, Hiroshi Tsujimura
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 
//  * Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of Oki Software Co., Ltd. nor the names of its
//    contributors may be used to endorse or promote products derived from
//    this software without specific prior written permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE. 

using System;
using System.Text;
using System.Net;
using System.Windows.Forms;
using System.Threading;
using System.Web;

[assembly: Tumblen3.Revision("$Header: /Tumblen3.root/Tumblen3/Tumblen3/Mixi.cs 5     09/06/08 15:07 Tsujimura543 $")]
namespace Tumblen3
{
    partial class Utility
    {
        /// <summary>
        /// 「mixi」関連処理群
        /// </summary>
        public class Mixi
        {
            /// <summary>
            /// 「mixi関連サービス」種別
            /// </summary>
            public enum ServiceType
            {
                Diary = 0,
                Echo = 1
            }

            /// <summary>
            /// 「mixi」関連サービスへ投稿します
            /// </summary>
            /// <param name="title">(ブックマーク投稿時)ブックマーク対象記事タイトル</param>
            /// <param name="url">(ブックマーク投稿時)ブックマーク対象記事URL</param>
            /// <param name="quote">発言、本文 または (ブックマーク投稿時)コメント</param>
            /// <param name="tags">(ブックマーク投稿時)タグ</param>
            /// <param name="type">「mixi関連サービス」種別</param>
            public static void PostArticle(
                string title, string url, string quote, string tags, ServiceType type)
            {
                switch (type)
                {
                    case ServiceType.Echo:
                        Echo.PostArticle(title, url, quote, tags);
                        break;
                }
            }

            #region 「mixi」へ login
            /// <summary>
            /// 「mixi」へ login します
            /// </summary>
            /// <param name="userName">メールアドレス</param>
            /// <param name="password">パスワード</param>
            /// <param name="cc">cookie格納用コンテナ</param>
            /// <returns>login に成功したか否か</returns>
            private static bool Login(string userName, string password, CookieContainer cc)
            {
                bool ret = false;

                string result = GetWebPage("http://mixi.jp/", cc);
                if (result == "")
                    return ret;

                string postData = "";
                postData = "next_url=" + EscapeUriString("/home.pl");
                postData += "&email=" + userName;
                postData += "&password=" + password;
                postData += "&sticky=on";

                Encoding encode = Encoding.GetEncoding("euc-jp");
                byte[] reqData = encode.GetBytes(postData);
                result = PostWebPage("http://mixi.jp/login.pl", reqData,
                                     "application/x-www-form-urlencoded", encode, cc);
                if (result != "" && result.Contains("http-equiv=\"refresh\""))
                {
                    int loc1 = result.IndexOf("http-equiv=\"refresh\"");
                    if (loc1 >= 0)
                    {
                        loc1 += "http-equiv=\"refresh\"".Length;

                        int loc2 = result.IndexOf("content=\"0;url=", loc1);
                        if (loc2 > 0)
                        {
                            loc1 = loc2 + "content=\"0;url=".Length;
                            loc2 = result.IndexOf('"', loc1);
                            if (loc2 > 0)
                            {
                                string url = result.Substring(loc1, loc2 - loc1);
                                if (url[0] == '/')
                                    url = "http://mixi.jp" + url;
                                result = GetWebPage(url, encode, cc);
                            }
                        }
                    }
                }
                if (result != "" && result.Contains("logout"))
                    ret = true;

                return ret;
            }

            private static CookieContainer _cc = null;
            private static DateTime _timeStamp = new DateTime(1970, 1, 1, 0, 0, 0);
            private static bool AlreadyLogin
            {
                get
                {
                    bool alreadyLogin = false;
                    if (_cc != null)
                    {
                        DateTime n = DateTime.Now;
                        TimeSpan d = new TimeSpan(1, 0, 0); // Cookie をキャッシュする時間
                        if (n - _timeStamp > d)
                        {
                            _cc = null;
                            Echo.PostKey = "";
                        }
                    }

                    if (_cc == null)
                    {
                        _cc = new CookieContainer();
                        alreadyLogin = Login(Setting.userNameForMixi, Setting.passwordForMixi, _cc);
                        if (!alreadyLogin)
                        {
                            _cc = null;
                            Echo.PostKey = "";
                        }
                        else
                            _timeStamp = DateTime.Now;
                    }
                    else
                        alreadyLogin = true;

                    return alreadyLogin;
                }
            }
            #endregion

            #region mixiエコー
            /// <summary>
            /// 「mixiエコー」関連処理群
            /// </summary>
            public class Echo
            {
                #region 「mixiエコー」へ投稿
                /// <summary>
                /// 「mixiエコー」へ発言を投稿します
                /// </summary>
                /// <param name="title">(ブックマーク投稿時)ブックマーク対象記事タイトル</param>
                /// <param name="url">(ブックマーク投稿時)ブックマーク対象記事URL</param>
                /// <param name="quote">発言 または (ブックマーク投稿時)コメント</param>
                /// <param name="tags">(ブックマーク投稿時)タグ</param>
                public static void PostArticle(string title, string url, string quote, string tags)
                {
                    if (Setting.userNameForMixi == null || Setting.userNameForMixi == "" ||
                        Setting.passwordForMixi == null || Setting.passwordForMixi == "")
                        return;

                    ParameterForPostArticle p = new ParameterForPostArticle();
                    p.title = title;
                    p.url = url;
                    p.quote = quote;
                    p.tags = tags;

                    Thread t = new Thread(new ParameterizedThreadStart(PostArticle));
                    t.Start(p);
                }

                public static string PostKey = "";
                private static void PostArticle(object data)
                {
                    ThreadCount++;
                    ParameterForPostArticle p = (ParameterForPostArticle)data;

                    Cursor preCursor = Cursor.Current;
                    Cursor.Current = Cursors.WaitCursor;

                    Encoding encode = Encoding.GetEncoding("euc-jp");
                    if (AlreadyLogin)
                    {
                        if (PostKey == "")
                        {
                            string result = GetWebPage("http://mixi.jp/recent_echo.pl", encode, _cc);
                            if (result != null && result != "")
                            {
                                int loc1 = result.IndexOf("name=\"post_key\" value=\"");
                                if (loc1 >= 0)
                                {
                                    loc1 += "name=\"post_key\" value=\"".Length;

                                    int loc2 = result.IndexOf('"', loc1);
                                    if (loc2 > 0)
                                    {
                                        PostKey = result.Substring(loc1, loc2 - loc1);
                                    }
                                }
                            }
                        }
                    }

                    if (PostKey.Length > 0) 
                    {
                        string postURL = "http://mixi.jp/add_echo.pl";
                        string postData = "";

                        if (p.url != null && p.url.Length > 0)
                        {
                            string monologue = "Bookmarked " + p.url + " - \"" + p.title + "\"";
                            string comment = "";
                            if (p.quote != null && p.quote != "")
                                comment = "\r\n" + p.quote;

                            postData = "body=" + HttpUtility.UrlEncode(monologue, encode);
                            postData += "::" + HttpUtility.UrlEncode(GetExtended(comment, p.tags), encode);
                        }
                        else
                        {
                            postData = "body=" + HttpUtility.UrlEncode(p.quote, encode);
                        }
                        postData += "&redirect=recent_echo";
                        postData += "&post_key=" + PostKey;

                        byte[] reqData = encode.GetBytes(postData);

                        string result = PostWebPage(postURL, reqData,
                                                    "application/x-www-form-urlencoded", encode, _cc);
                        if (result != null && result != "")
                        {
                            if (result.Contains(p.quote))
                            {
                                if (Setting.SupressSuccessDialog == false)
                                {
                                    MessageBox.Show(Resource1.success_post_toMixiEcho_msg,
                                                    Resource1.success_post_toMixiEcho);
                                }
                            }
                        }
                    }

                    Cursor.Current = preCursor;
                    ThreadCount--;
                }
                #endregion
            }
            #endregion
        }
    }

    #region 各種設定
    partial class Setting
    {
        #region for social bookmarks
        #endregion

        #region for microblogs
        /// <summary>
        /// 「mixiエコー」を発言投稿先として使うか否か
        /// </summary>
        public bool UseMixiEchoForTweet
        {
            set { Tumblen3.Default.UseMixiEchoForTweet = value; }
            get { return Tumblen3.Default.UseMixiEchoForTweet; }
        }
        #endregion

        #region settings for mixi account
        /// <summary>
        /// 「mixi」にログインするときのメールアドレス
        /// </summary>
        public string userNameForMixi = "";

        /// <summary>
        /// 「mixi」にログインするときのパスワード
        /// </summary>
        public string passwordForMixi = "";
        #endregion
    }
    #endregion

    #region Form2(設定変更ダイアログ)関連
    partial class Form2
    {
        #region for social bookmarks
        #endregion

        #region for microblogs
        /// <summary>
        /// 「mixi エコー」を発言投稿先として使うか否か
        /// </summary>
        public bool postMixiEcho
        {
            set { Tumblen3.Default.UseMixiEchoForTweet = value; }
            get { return Tumblen3.Default.UseMixiEchoForTweet; }
        }
        #endregion

        #region settings for mixi account
        /// <summary>
        /// 「mixi」にログインするときの ID
        /// </summary>
        public string userNameForMixi
        {
            set { Tumblen3.Default.MixiUserName = value; }
            get { return Tumblen3.Default.MixiUserName; }
        }

        /// <summary>
        /// 「mixi」にログインするときのパスワード
        /// </summary>
        public string passwordForMixi
        {
            set { Utility.Setting.passwordForMixi = value; }
            get { return Utility.Setting.passwordForMixi; }
        }
        #endregion
    }
    #endregion
}
